package com.yssoft.controller.app.purchase;

import com.yssoft.entity.purchase.TRecipientDetail;
import com.yssoft.service.purchase.RecipientDetailService;
import com.yssoft.utils.AppUtil;
import com.yssoft.vo.TRecipientAttVo;

import org.apache.commons.codec.DecoderException;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.List;
import java.util.Map;

/**
 * @author 戈超
 * @time 2018/5/02 下午 13:34
 * @  收货管理控制器
 */
@CrossOrigin//解决跨域session问题
@Controller
@RequestMapping(value = "/app/recipient")
public class RecipientDetailController {
	private static Logger logger=Logger.getLogger(RecipientDetailService.class);

	@Resource
	private RecipientDetailService recipientDetailService;
	
	/**
	 * 查询待收货列表
	 * @param page
	 * @param limit
	 * @param userId
	 * @param supplierId
	 * @param supplyTime
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "toReceivedList", method = RequestMethod.POST)
	public Object toReceivedList(int currentPage1, int pageSize1, String userId, String supplierId, String supplyTime, HttpServletRequest request){
		String msg = "待收货列表查询";
    	try{
    		List<Map<String,Object>> pageList = recipientDetailService.toReceiveList(currentPage1, pageSize1, userId, supplierId, supplyTime, request);
        	return AppUtil.returnListJson("1", msg+"成功!", pageList);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnListJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 查询已收货列表
	 * @param page
	 * @param limit
	 * @param userId
	 * @param supplierId
	 * @param supplyTime
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "receivedList", method = RequestMethod.POST)
	public Object receivedList(int currentPage2, int pageSize2, String userId, String supplierId, String supplyTime, HttpServletRequest request){
		String msg = "已收货列表查询";
    	try{
    		List<Map<String,Object>> pageList = recipientDetailService.receiveList(currentPage2, pageSize2, userId, supplierId, supplyTime, request);
        	return AppUtil.returnListJson("1", msg+"成功!", pageList);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnListJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 保存收货单
	 * @param transactionPicfile
	 * @param qualifiedpicfile
	 * @param tRecipientDetail
	 * @param tRecipientAttVo
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "receipt", method = {RequestMethod.POST,RequestMethod.GET})
	public Object receipt(TRecipientDetail tRecipientDetail, TRecipientAttVo tRecipientAttVo, HttpServletRequest request){
		String msg = "收货";
    	try{
    		tRecipientDetail.setStat("1");	//状态-收货
    		recipientDetailService.receipt(tRecipientDetail, tRecipientAttVo, request);
        	return AppUtil.returnMapJson("1", msg+"成功!", null);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnMapJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 退回收货单
	 * @param transactionPicfile
	 * @param qualifiedpicfile
	 * @param tRecipientDetail
	 * @param tRecipientAttVo
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "sendBack", method = {RequestMethod.POST,RequestMethod.GET})
	public Object sendBack(TRecipientDetail tRecipientDetail, TRecipientAttVo tRecipientAttVo, HttpServletRequest request){
		String msg = "退回";
    	try{
    		tRecipientDetail.setStat("2");	//状态-退回
    		tRecipientDetail.setRefQuantity(tRecipientDetail.getAccepQuantity());
    		tRecipientDetail.setActualQuantity(new BigDecimal(0));
    		recipientDetailService.receipt(tRecipientDetail, tRecipientAttVo, request);
        	return AppUtil.returnMapJson("1", msg+"成功!", null);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnMapJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 收货记录查看
	 * @param tDdId
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "receiptRecord", method = {RequestMethod.POST,RequestMethod.GET})
	public Object receiptRecord(String tDdId, HttpServletRequest request){
		String msg = "收货记录查看";
		try{
    		Map<String,Object> pageList = recipientDetailService.queryReceiptRecord(tDdId,request);
        	return AppUtil.returnMapJson("1", msg+"成功!", pageList);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnMapJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 收货单查看
	 * @param tDdId
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "receiptRecordList", method = {RequestMethod.POST,RequestMethod.GET})
	public Object receiptRecordList(int currentPage, int pageSize, String startTime, String endTime, HttpServletRequest request){
		String msg = "收货单查看";
		try{
    		List<Map<String,Object>> pageList = recipientDetailService.queryReceiptRecordList(currentPage, pageSize, startTime, endTime, request);
        	return AppUtil.returnListJson("1", msg+"成功!", pageList);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnListJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 查询仓库列表
	 * @param request
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "queryWarehouseList", method = RequestMethod.POST)
	public Object queryWarehouseList(Integer tCId,HttpServletRequest request){
		String msg = "仓库列表查询";
		try{
    		List<Map<String,Object>> warehouseList = recipientDetailService.queryWarehouseList(tCId,request);
        	return AppUtil.returnListJson("1", msg+"成功!", warehouseList);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnListJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 获取溯源过程信息
	 * @author 戈超
	 * @param productId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "getTraceProcessInfo", method = RequestMethod.POST)
    public Object getTechnologyInfo(String recipientId,HttpServletRequest request) {
        try {
            List<Map<String, Object>> technologyList = recipientDetailService.findTechnologyByProduct(request);
            for (Map<String, Object> stringObjectMap : technologyList) {
                List<Map<String, Object>> index = recipientDetailService.findIndexAndValueByProcessingTechnic(stringObjectMap.get("id") + "",recipientId);
                stringObjectMap.put("technicIndex", index);
            }
            return AppUtil.returnListJson("1", "查询成功", technologyList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AppUtil.returnMapJson("0", "查询失败", null);
        }
    }
	
	/**
	 * 查询溯源对应的指标信息和值
	 * @author 戈超
	 * @param technologyId
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "getTechnologyIndexAndValue", method = RequestMethod.POST)
    public Object getTechnologyIndexAndValue(String technologyId, String recipientId) {
        if (technologyId == null && technologyId.length() <= 0) {
            return AppUtil.returnMapJson("0", "请传递溯源过程实体id", null);
        }
        try {
            List<Map<String, Object>> technologyList = recipientDetailService.findIndexAndValueByProcessingTechnic(technologyId, recipientId);
          
            return AppUtil.returnListJson("1", "查询成功", technologyList);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AppUtil.returnMapJson("0", "查询失败", null);
        }
    }
	
	/**
	 * 修改溯源指标采集的数据(正常文本值和附件值都用gValue来接受根据加工工艺中的指标类型判断保存时候是否有附件, 指标值使用工艺指标id + Value来接收)
	 * @param indicatorIds
	 * @param recipientId
	 * @param request
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "updateTechnologyIndicators", method = RequestMethod.POST)
    public Object updateTechnologyIndicators(String[] indicatorIds, String recipientId, HttpServletRequest request)  {
        try {
            if(request.getHeader("content-type")!=null&&"application/x-www-form-urlencoded".equals(request.getHeader("content-type"))){
                 return null;//不支持断点续传，直接返回null即可
            }
            recipientDetailService.editTechnologyIndicators(indicatorIds, recipientId, request);
            return  AppUtil.returnMapJson("1", "保存成功!", null);
        } catch (IOException e) {
            return AppUtil.returnMapJson("0", "保存失败!", null);
        } catch (DecoderException e) {
            return AppUtil.returnMapJson("0", "保存失败!", null);
        } catch (ParseException e) {
            return AppUtil.returnMapJson("0", "保存失败!", null);
        }
    }
    
	/**
	 * 删除溯源信息
	 * @param pid
	 * @param request
	 * @return
	 */
	@ResponseBody
    @RequestMapping(value = "indexDelete", method = RequestMethod.POST)
    public Object indexDelete(String[] indicatorIds,Integer recipientId,  HttpServletRequest request){
		String msg = "溯源信息删除";
		try{
			recipientDetailService.indexDelete(recipientId,indicatorIds, request);
        	return AppUtil.returnListJson("1", msg+"成功!", null);
    	} catch (Exception e) {
    		logger.info(msg+"失败："+e.getMessage());
    		return AppUtil.returnListJson("0", msg+"失败!", null);
		}
	}
	
	/**
	 * 在服务器中删除图片
	 * @param fileKey
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "deleteFile", method = RequestMethod.POST)
    public Object deleteFile(String fileKey){
        try {
            int fileUrlIndex= fileKey.indexOf("/files");
            String newFileUrl = fileKey.substring(fileUrlIndex);
            recipientDetailService.deleteFileByUrl(newFileUrl);
            return AppUtil.returnMapJson("1","删除成功",null);
        } catch (Exception e) {
            e.printStackTrace();
            return  AppUtil.returnMapJson("0","删除失败",null);
        }
       
    }
	
	/**
	 * 图片上传
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "uploadImage", method = RequestMethod.POST)
	public Object uploadImage(HttpServletRequest request) throws Exception {
		try{
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
			MultipartFile mFile = mRequest.getFile("img");
			Map<String, Object> fileNames = recipientDetailService.compressUploadedFile(mFile);
			return AppUtil.returnMapJson("1", "上传成功!", fileNames);
		} catch (Exception e) {
			return AppUtil.returnMapJson("0", "上传失败!", null);
		}
	}
}
